/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ykht.proj.activity.entity.VOrderCard;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.annotation.Inner;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.FxReturnTypeEnum;
import com.ykht.proj.coupon.Enum.RewardPersonEnum;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.entity.FxMerchantAccount;
import com.ykht.proj.coupon.entity.FxRewardPerson;
import com.ykht.proj.coupon.entity.FxShare;
import com.ykht.proj.coupon.service.FxRewardPersonService;
import com.ykht.proj.coupon.vo.FxRewardPersonVo;
import com.ykht.proj.coupon.vo.FxRewardPersonVo4PC;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;


/**
 * c端奖励记录表
 *
 * @author proj code generator
 * @date 2021-08-12 14:10:39
 */
@RestController
@AllArgsConstructor
@RequestMapping("/fxrewardperson" )
@Api(value = "fxrewardperson", tags = "c端奖励记录表管理")
@Slf4j
public class FxRewardPersonController {

    private final  FxRewardPersonService fxRewardPersonService;

	/**
	 * 用户 服务 Api
	 */
	private final RemoteUserService remoteUserService;


	@ApiOperation(value = "分页查询 c端奖励记录表", notes = "分页查询 c端奖励记录表")
	@GetMapping("/excel" )
	public void  excel(Page page, FxRewardPersonVo fxRewardPersonVo) throws IOException {
		log.info("->分页查询 c端奖励记录表 :{}", page, fxRewardPersonVo);
		page.setSize(10000);
		fxRewardPersonVo.setStatus(2);
		IPage<FxRewardPersonVo> iPage = fxRewardPersonService.getFxRewardPersonPage(page, fxRewardPersonVo);
		List<FxRewardPersonVo> records = iPage.getRecords();
		if (null != records && records.size() > 0){
			List<Long> ids = records.stream().filter(o->o.getLoginId()!=null).map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(ids);
			records.stream().filter(o->o.getLoginId()!=null).forEach(itme -> {
//				优惠券类型0无门槛1满减
				itme.setCouponTypeName(itme.getCouponType()==0?"无门槛":"满减");
				userList.stream().forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
					}
				});
			});
		}
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		ServletOutputStream out = response.getOutputStream();
		ExcelWriter writer = ExcelUtil.getWriter(true);

		//自定义标题别名
		writer.addHeaderAlias("id", "id");
		writer.addHeaderAlias("orderNumber", "订单编号");
		writer.addHeaderAlias("couponName", "优惠券名称");
		writer.addHeaderAlias("couponTypeName", "优惠券类型");
		writer.addHeaderAlias("lowMoney", "最低消费金额");
		writer.addHeaderAlias("cnMoney", "消费金额");
		writer.addHeaderAlias("reductionMoney", "减免金额/折扣");
		writer.addHeaderAlias("fyName", "领取人");
		writer.addHeaderAlias("username", "核销人");
		writer.addHeaderAlias("shopName", "核销门店");
		writer.addHeaderAlias("brandName", "所属品牌");
		writer.addHeaderAlias("money", "贡献佣金");
		writer.addHeaderAlias("verificationTime4String", "核销时间");

// 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
		writer.setOnlyAlias(true);
		writer.write(records, true);

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		response.setHeader("Content-Disposition","attachment;filename="+System.currentTimeMillis()+".xlsx");

		writer.flush(out, true);
		writer.close();
		IoUtil.close(out);
	}

	/**
     * 分页查询 c端奖励记录表
     * @param page 分页对象
     * @param fxRewardPersonVo c端奖励记录表
     * @return
     */
    @ApiOperation(value = "分页查询 c端奖励记录表", notes = "分页查询 c端奖励记录表")
    @GetMapping("/page" )
    public R<FxRewardPersonVo4PC> getFxRewardPersonPage(Page page, FxRewardPersonVo fxRewardPersonVo) {
		log.info("->分页查询 c端奖励记录表 :{}", page, fxRewardPersonVo);
		fxRewardPersonVo.setStatus(2);
		IPage<FxRewardPersonVo> iPage = fxRewardPersonService.getFxRewardPersonPage(page, fxRewardPersonVo);
		List<FxRewardPersonVo> records = iPage.getRecords();
		if (null != records && records.size() > 0){
			List<Long> ids = records.stream().filter(o->o.getLoginId()!=null).map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(ids);
			records.stream().filter(o->o.getLoginId()!=null).forEach(itme -> {
				userList.stream().forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
					}
				});
			});
			iPage.setRecords(records);
		}
		FxRewardPersonVo4PC pc = new FxRewardPersonVo4PC();
		pc.setPage(iPage);
		pc.setUseNum(iPage.getTotal());
		Integer shareNum = new FxShare().selectCount(Wrappers.lambdaQuery(FxShare.class).eq(FxShare::getPerId, fxRewardPersonVo.getPersonId()));
		pc.setShareNum(shareNum);
		new FxRewardPerson().selectList(Wrappers.lambdaQuery(FxRewardPerson.class).eq(FxRewardPerson::getPersonId,fxRewardPersonVo.getPersonId()).eq(FxRewardPerson::getStatus, RewardPersonEnum.pushed.getValue()))
				.stream().map(FxRewardPerson::getMoney).reduce(BigDecimal::add).ifPresent(o->pc.setUseMoney(o));
        return R.ok(pc);
    }


	/**
	 * 分页查询 品牌的消费记录表
	 * @param page 分页对象
	 * @param fxRewardPersonVo c端奖励记录表
	 * @return
	 */
	@ApiOperation(value = "分页查询 品牌的消费记录表", notes = "分页查询 品牌的消费记录表")
	@GetMapping("/getBrandConsumptionPage" )
	public R<IPage<FxRewardPersonVo>> getBrandConsumptionPage(Page page, FxRewardPersonVo fxRewardPersonVo) {
		log.info("->分页查询 品牌的消费记录表 :{}", page, fxRewardPersonVo);
		if (fxRewardPersonVo.getId()!=null && SecurityUtils.getUser().getUserType()== UserTypeEnum.admin.getValue()) {
			FxMerchantAccount account = new FxMerchantAccount().selectOne(Wrappers.lambdaQuery(FxMerchantAccount.class).eq(FxMerchantAccount::getId, fxRewardPersonVo.getId()));
			fxRewardPersonVo.setBrandId(account.getTatId());
		}

		if (SecurityUtils.getUser().getUserType()== UserTypeEnum.brand.getValue()) {
			fxRewardPersonVo.setBrandId(SecurityUtils.getSjId());
		}
		fxRewardPersonVo.setStatus(FxReturnTypeEnum.RETURN.getValue());
		IPage<FxRewardPersonVo> iPage = fxRewardPersonService.getBrandConsumptionPage(page, fxRewardPersonVo);
		List<FxRewardPersonVo> records = iPage.getRecords();
		if (null != records && records.size() > 0){
			List<Long> ids = records.stream().filter(o->o.getLoginId()!=null).map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(ids);
			records.stream().filter(o->o.getLoginId()!=null).forEach(itme -> {
				userList.stream().filter(o->o.getUserId()!=null).forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
						itme.setUserPhone(user.getPhone());
					}
				});
			});
			iPage.setRecords(records);
		}
		return R.ok(iPage);
	}
	@ApiOperation(value = " 品牌的消费记录导出到excel")
	@GetMapping("/getBrandConsumption4Excel" )
	public void getBrandConsumption4Excel(FxRewardPersonVo fxRewardPersonVo) throws IOException {
		log.info("->品牌的消费记录导出到excel :{}" , fxRewardPersonVo);
		if (fxRewardPersonVo.getId()!=null && SecurityUtils.getUser().getUserType()== UserTypeEnum.admin.getValue()) {
			FxMerchantAccount account = new FxMerchantAccount().selectOne(Wrappers.lambdaQuery(FxMerchantAccount.class).eq(FxMerchantAccount::getId, fxRewardPersonVo.getId()));
			fxRewardPersonVo.setBrandId(account.getTatId());
		}

		if (SecurityUtils.getUser().getUserType()== UserTypeEnum.brand.getValue()) {
			fxRewardPersonVo.setBrandId(SecurityUtils.getSjId());
		}
		fxRewardPersonVo.setStatus(FxReturnTypeEnum.RETURN.getValue());
		List<FxRewardPersonVo> records = fxRewardPersonService.getBrandConsumptionPage(fxRewardPersonVo);
		if (null != records && records.size() > 0){
			List<Long> ids = records.stream().filter(o->o.getLoginId()!=null).map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(ids);
			records.stream().filter(o->o.getLoginId()!=null).forEach(itme -> {
				userList.stream().filter(o->o.getUserId()!=null).forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
						itme.setUserPhone(user.getPhone());
					}
				});
			});
		}
		ServletOutputStream out = null;
		ExcelWriter writer = null;
		try {
			HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
			out = response.getOutputStream();
			writer = ExcelUtil.getWriter(true);

			//自定义标题别名
			writer.addHeaderAlias("orderNumber", "订单编号");
			writer.addHeaderAlias("couponName", "优惠券名称");
			writer.addHeaderAlias("verificationCode", "优惠券码");
			writer.addHeaderAlias("fyName", "客户");
			writer.addHeaderAlias("shopName", "核销门店");
			writer.addHeaderAlias("username", "核销人");
			writer.addHeaderAlias("money", "贡献佣金");
			writer.addHeaderAlias("verificationTime4String", "核销时间");

			// 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
			writer.setOnlyAlias(true);
			writer.write(records, true);

			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
			String fileName = java.net.URLEncoder.encode("消费记录", "UTF-8");
			String agent = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("USER-AGENT").toLowerCase();
			if (agent.contains("firefox")) {
				response.setCharacterEncoding("utf-8");
				response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls");
			} else {
				response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.flush(out, true);
			writer.close();
			IoUtil.close(out);
		}


	}

	public static void main(String[] args) {
		System.out.println(URLDecoder.decode("消费记录", Charset.forName("utf-8")));
	}


	/**
     * 通过id查询c端奖励记录表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('coupon_fxrewardperson_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(fxRewardPersonService.getById(id));
    }

    /**
     * 新增c端奖励记录表
     * @param fxRewardPerson c端奖励记录表
     * @return R
     */
    @ApiOperation(value = "新增c端奖励记录表", notes = "新增c端奖励记录表")
    @SysLog("新增c端奖励记录表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('coupon_fxrewardperson_add')" )
    public R save(@RequestBody FxRewardPerson fxRewardPerson) {
        return R.ok(fxRewardPersonService.save(fxRewardPerson));
    }

    /**
     * 修改c端奖励记录表
     * @param fxRewardPerson c端奖励记录表
     * @return R
     */
    @ApiOperation(value = "修改c端奖励记录表", notes = "修改c端奖励记录表")
    @SysLog("修改c端奖励记录表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('coupon_fxrewardperson_edit')" )
    public R updateById(@RequestBody FxRewardPerson fxRewardPerson) {
        return R.ok(fxRewardPersonService.updateById(fxRewardPerson));
    }

    /**
     * 通过id删除c端奖励记录表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除c端奖励记录表", notes = "通过id删除c端奖励记录表")
    @SysLog("通过id删除c端奖励记录表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('coupon_fxrewardperson_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(fxRewardPersonService.removeById(id));
    }
    @ApiOperation(value = "导出消费记录表")
	@PostMapping("ExportExcel")
	@Inner(false)
	public   void  getExportExcel(HttpServletResponse response){
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("消费记录表");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCell cell = row.createCell((short) 0);
		//		序号 订单编号 优惠券名称 优惠券码 核销门店 客户 核销人 佣金 核销时间
		cell.setCellValue("序号");
		cell=row.createCell((short)1);
		cell.setCellValue("订单编号");
		cell=row.createCell((short)2);
		cell.setCellValue("优惠劵名称");
		cell=row.createCell((short)3);
		cell.setCellValue("优惠券码");
		cell=row.createCell((short)4);
		cell.setCellValue("核销门店");
		cell=row.createCell((short)5);
		cell.setCellValue("客户");
		cell=row.createCell((short)6);
		cell.setCellValue("核销人");
		cell=row.createCell((short)7);
		cell.setCellValue("佣金");
		cell=row.createCell((short)8);
		cell.setCellValue("核销时间");
		List<FxRewardPersonVo>list=fxRewardPersonService.getExport();
		for (int i = 0; i < list.size(); i++) {
			HSSFRow row1 = sheet.createRow((short) i + 1);
			FxRewardPersonVo vo = list.get(i);
			//		序号 订单编号 优惠券名称 优惠券码 核销门店 客户 核销人 佣金 核销时间
			row1.createCell((short)0).setCellValue(vo.getId());
			row1.createCell((short)1).setCellValue(vo.getOrderNumber());
			row1.createCell((short)2).setCellValue(vo.getCouponName());
			row1.createCell((short)3).setCellValue(vo.getVerificationCode());
			row1.createCell((short)4).setCellValue(vo.getVerificationShop());
			row1.createCell((short)5).setCellValue(vo.getFyName());
			row1.createCell((short)6).setCellValue(vo.getVerificationPersonName());
			BigDecimal returnMoney = vo.getReturnMoney();
			if(returnMoney!=null){
				row1.createCell((short)7).setCellValue(returnMoney.toString());
			}
			String Time=null;
			if(Time!=null &&Time!=""){
				 Time = vo.getVerificationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			}
			row1.createCell((short)8).setCellValue(Time);
		}
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("2021-09-03.xls", "UTF-8"));
			response.setHeader("Connection", "close");
			response.setHeader("Content-Type", "application/octet-stream");
			wb.write(response.getOutputStream());
			wb.close();
		}catch (Exception e){
			System.out.println("导出失败");
			e.printStackTrace();
		}
	}
}
